package com.example.webmodule.task;

import cn.hutool.cron.CronUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.webmodule.common.RegistryType;
import com.example.webmodule.strategy.RegistrySelectStrategy;
import com.example.webmodule.strategy.RegistryStrategyFactory;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName EY-ScheduledTasks
 * @Description com.example.webmodule.task
 * @Author menyj
 * @Date 2025/3/28
 **/
@Component
public class ScheduledTasks {

    @Autowired(required = false)
    @Qualifier(value = "schedulerThreadPoolTaskExecutor")
    private ThreadPoolTaskExecutor taskExecutor;

    @Value("${ey.task.scan-interface.cron}")
    private String cronExpress;

    @Autowired
    private RegistryStrategyFactory registryStrategyFactory;

    @Autowired
    CacheManager cacheManager;

    @PostConstruct
    public void scheduleTasks() {
        if (null != taskExecutor) {
            RegistrySelectStrategy registrySelectStrategy = registryStrategyFactory.getStrategy();
            // 启动定时任务
            CronUtil.setMatchSecond(true);
            CronUtil.schedule("scanInterface", cronExpress, () -> {
                taskExecutor.execute(() -> {
                    List<String> currentServices =  registrySelectStrategy.getServices();
                    List<String> knownServices = cacheManager.getCache(
                            RegistryType.NACOS.name()).get("knownServices", List.class);
                    if (CollectionUtils.isEmpty(knownServices)) {
                        cacheManager.getCache(
                                RegistryType.NACOS.name()).put("knownServices", currentServices);
                    }
                    else {
                        currentServices.stream()
                                .filter(service -> !knownServices.contains(service))
                                .forEach(newService -> {
                                    registrySelectStrategy.subscribe(newService);
                                    // 处理新服务逻辑
                                    knownServices.add(newService);
                                });
                        cacheManager.getCache(
                                RegistryType.NACOS.name()).put("knownServices", knownServices);
                    }
                });
            });
            CronUtil.start(true);
        }
    }
}
